<?php

declare (strict_types = 1);

namespace own\middleware;

use own\enum\CacheKey;
use own\helps\RespCode;
use own\helps\JwtAuth;
use own\interface\OwnMiddlewareInterface;
use think\facade\Cache;
use think\facade\Config;
use think\Response;

class ApiMiddleware extends OwnMiddlewareInterface
{
    /**
     * 处理请求信息
     * @param Request $request
     * @param string $token
     * @param Closure  $next
     * @return Response
     */
    public function handleRequest($request, $token, $next)
    {
        $request->port = 2;//端口：1管理端api 2客户端api
        if (!$token) {
            tips('请登录账户', RespCode::NOT_LOGIN);
        }
        $member = make(JwtAuth::class)->verify((string) $token);
        if (!$member) {
            tips('请登录账户', RespCode::NOT_LOGIN);
        }
        $cacheToken = Cache::store('redis')->hget(CacheKey::OWN_MSIGN, 'm' . $member->uid);
        if (!$cacheToken) {
            tips('请重新登录', RespCode::NOT_LOGIN);
        }
        if (Config::get('jwt.member_login') == 'sso' && $cacheToken != $token) {
            tips('账号已被登出,请重新登录', RespCode::NOT_LOGIN);
        }
        $request->uid = (int) $member->uid;
        $request->auth = $member;
        return $next($request);
    }
}
